<template>
  <span class="inline-text-container">
    <template v-for="(segment, index) in parsedSegments" :key="index">
      <template v-if="segment.isField">
        <dynamic-form :form-data="formData" :components="[segment]" class="inline-input" />
      </template>
      <el-form-item v-else>
        <span class="inline-text-segment">{{ segment.text }}</span>
      </el-form-item>
    </template>
  </span>
</template>

<script setup>
import { computed } from 'vue';
import DynamicForm from './DynamicForm.vue';

const props = defineProps({
  content: String,
  fields: {
    type: Array,
    default: () => []
  },
  formData: {
    type: Object,
    required: true
  }
});

const parsedSegments = computed(() => {
  const regex = /\{\{(\w+)}}/g;
  let lastIndex = 0;
  const segments = [];

  props.content.replace(regex, (match, field, offset) => {
    if (offset > lastIndex) {
      segments.push({
        text: props.content.slice(lastIndex, offset),
        isField: false
      });
    }

    const fieldConfig = props.fields.find(f => f.field === field) || { field };
    segments.push({
      type: 'el-input', // 默认组件
      ...fieldConfig,
      isField: true
    });

    lastIndex = offset + match.length;
    return match;
  });

  if (lastIndex < props.content.length) {
    segments.push({
      text: props.content.slice(lastIndex),
      isField: false
    });
  }

  return segments;
});
</script>

<style scoped>
.inline-text-container {
  display: inline-flex;
  align-items: center;
  flex-wrap: wrap;
  line-height: 32px;
}

.inline-input {
  width: 120px;
  margin: 0 4px;

  :deep(.el-input__inner) {
    border-radius: 4px;
    padding: 0 8px;
    vertical-align: baseline;
  }
}

.inline-text-segment {
  vertical-align: middle;
}
</style>